float average1 = 0;
float middle1 = 500.0;
float average2 = 0;
float middle2 = 500.0;
float average3 = 0;
float middle3 = 500.0;
float average4 = 0;
float middle4 = 500.0;
float threshold = 2.5;

void setup() {          
  Serial.begin(9600);
  delay(1000);
  middle1 = findAverage(0, 0);
  middle2 = findAverage(1, 0);
  middle3 = findAverage(2, 0);
  middle4 = findAverage(3, 0);
  Serial.print("middle1 is ");
  Serial.print(middle1);  
  Serial.print("middle2 is ");
  Serial.print(middle2);  
  Serial.print("middle3 is ");
  Serial.print(middle3);  
  Serial.print("middle4 is ");
  Serial.println(middle4);  
  average1 = findAverage(0, middle1);
  average2 = findAverage(1, middle2);
  average3 = findAverage(2, middle3);
  average4 = findAverage(3, middle4);
  Serial.print("average1 from ");
  Serial.print(middle1);
  Serial.print(" is ");
  Serial.println(average1);
  Serial.print("average2 from ");
  Serial.print(middle2);
  Serial.print(" is ");
  Serial.println(average2);
  Serial.print("average3 from ");
  Serial.print(middle3);
  Serial.print(" is ");
  Serial.println(average3);
  Serial.print("average4 from ");
  Serial.print(middle4);
  Serial.print(" is ");
  Serial.println(average4);
}

float findAverage(int pin, int middle) {
  Serial.print("calculating...");
  int samples = 10000;
  float total = 0.0;
  for (int i = 0; i < samples; i++) {
    int value = readMics(pin, middle);
    total += value;
  }
  
  float average = total / samples;
  Serial.println("done!");
  return average;
}

void loop() {
  int value1 = readMics(0, middle1);
  int value2 = readMics(1, middle2);
  int value3 = readMics(2, middle3);
  int value4 = readMics(3, middle4);

  int offset = (value1 - average1) + (value2 - average2) + (value3 - average3) + (value4 - average4);
  if (offset > 80) {
    Serial.print(offset);
    Serial.println("");
  }
  /*
  if (value1 > average1 * threshold) {
    Serial.print("1: ");
    Serial.print(value1);
    Serial.println(" ");
  } else if (value2 > average2 * threshold) {
    Serial.print("2: ");
    Serial.print(value2);
    Serial.println(" ");
  } else if (value3 > average3 * threshold) {
    Serial.print("3: ");
    Serial.print(value3);
    Serial.println(" ");
  } else if (value4 > average4 * threshold) {
    Serial.print("4: ");
    Serial.print(value4);
    Serial.println(" ");
  }
  */

  delay(10);
}

int readMics(int pin, int middle) {
  int value = middle - analogRead(pin);
  return abs(value);
//  value2 = analogRead(1);  
//  value3 = analogRead(2);  
//  value4 = analogRead(3);  
}
